#!/bin/bash

source ./envsetup

#set -v

usage() {
        echo "Usage:"
        echo "  [CONFIG=<config>] ./build_linux.sh [-h] [-d] [-c | -a | -m]"
        echo "  -h: display usage"
        echo "  -d: build 32-bit kernel"
        echo "  -c: checkdtb"
        echo "  -a: make distclean"
	echo "  -m: make menuconfig"
}

while getopts ":hdcam" opt
do
        case $opt in
        h)
                O_HELP=y
                ;;
        d)
                O_32=y
                ;;
        c)
                O_CHKDTB=y
                ;;
        a)
                O_MAKE_ALL=y
                ;;
	m)
		O_MAKE_MENUCFG=y
		;;
        ?)
                echo "there is unrecognized parameter."
                usage
                exit 1
                ;;
    esac
done

#echo "O_HELP = $O_HELP"
#echo "O_32 = $O_32"
#echo "O_CHKDTB = $O_CHKDTB"
#echo "O_MAKE_ALL = $O_MAKE_ALL"
#echo "O_MAKE_MENUCFG = $O_MAKE_MENUCFG"

if [ "$O_HELP" = "y" ]; then
	usage
	exit 0
fi

# FIXME: following action on setting OUT is duplicated with env
# may need to move to build_linux.sh

# default config
if [[ -z "${CONFIG}" ]]; then
        CONFIG=defconfig
fi

if [ "$O_32" = "y" ]; then
	CONFIG="defconfig 32-bit.config"
	exit 0
fi

print_env

echo "-------------------"
echo "CONFIG=$CONFIG"
echo "==================="

read -p "Would you continue? [N/y]:" choice
case $choice in
Y | y)
	echo "======> Continue ......"
	;;
*)
	echo "======> Cancelled ...... Quitting now."
	exit
	;;
esac

# FIXME: just to make code simple
# "-c" only take effective when CONFIG=defconfig, don't use it for other CONFIGs
if [ "$O_CHKDTB" == "y" ] && [ "$CONFIG" == "defconfig" ]; then
	echo "======> Start checking dtb ......"

	pushd $PATH_LINUX

	rm -f $OUT/arch/riscv/boot/dts/$VENDOR_NAME/$DTB_FILE
	make -j$(nproc) O=$OUT CHECK_DTBS=y W=1 $VENDOR_NAME/$DTB_FILE

	#make -j$(nproc) O=$OUT DT_CHECKER_FLAGS=-m dt_binding_check DT_SCHEMA_FILES=Documentation/devicetree/bindings/pwm/sophgo,sg2042-pwm.yaml

	popd

	exit
fi

if [ "$O_MAKE_MENUCFG" = "y" ]; then
	echo "======> Start making menuconfig ......"
	pushd $PATH_LINUX
	make O=$OUT menuconfig
	popd
	exit
fi

echo "======> Start building ......"

pushd $PATH_LINUX

if [ "$O_MAKE_ALL" = "y" ]; then
	echo "======> Cleanup for FULLY building ......"
	rm -rf $OUT
	mkdir $OUT

	make O=$OUT $CONFIG

	./scripts/kconfig/merge_config.sh -O $OUT -m $OUT/.config $CWD/configs/$SOC_TYPE.config

#	./scripts/config --file $OUT/.config -e DYNAMIC_DEBUG
fi

make -j$(nproc) O=$OUT W=1 

popd


